import hashlib

from flask import Flask, request, json
from sqlalchemy import create_engine, Table
from sqlalchemy.orm import sessionmaker, declarative_base, scoped_session

app = Flask(__name__)

# 创建引擎，链接数据库
engine = create_engine('mysql+pymysql://root:admin@127.0.0.1:3306/mumu', echo=True)
# 打开数据库的连接会话
session = sessionmaker(engine)
# 保证线程安全
db_session = scoped_session(session)
# 获取基类
Base = declarative_base()


class User(Base):
    # 表结构反射加载
    __table__ = Table("user", Base.metadata, autoload_with=engine)

@app.route('/reg', methods=['POST'])
def reg():
    request_data = request.data
    request_data = json.loads(request_data)
    username = request_data["username"]
    password = request_data["password"]
    nickname = request_data["nickname"]
    picture = request_data["picture"]
    # md5
    password = hashlib.md5(password.encode()).hexdigest()
    print("=====md5==", password)

    insert_data = {
        "username": username,
        "nickname": nickname,
        "picture": picture,
        "password": password
    }
    print(User(**insert_data))
    user = User(**insert_data)
    db_session.add(user)
    db_session.commit()

    return "注册成功"

if __name__ == '__main__':
    app.run(debug=True)